package com.telrob.antlr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.telrob.antlr.type.DeclaraListType;
import com.telrob.antlr.type.DeclaraType;
import com.telrob.antlr.type.DigitType;
import com.telrob.antlr.type.FunctionHeaderType;
import com.telrob.antlr.type.FunctionType;
import com.telrob.antlr.type.IdType;
import com.telrob.antlr.type.IntType;
import com.telrob.antlr.type.StringType;
import com.telrob.antlr.type.StringValue;
import com.telrob.antlr.type.SymbolType;
import com.telrob.antlr.type.XnType;
import com.telrob.antlr.utils.StringUtils;

public class ProcessUtils extends XnType {
	private List<DeclaraListType> declaraList=new ArrayList<DeclaraListType>();
	private List<FunctionType> functionList=new ArrayList<FunctionType>();
	private Map<String,String> functionName=new HashMap<String,String>();
	private Map<String,SymbolType> symbolName=new HashMap<String,SymbolType>();
	
	public void addDeclaraList(DeclaraListType declara) {
		declaraList.add(declara);
	}
	
	public void addFunction(FunctionType func) {
		functionList.add(func);
	}
	
	
	private void processDeclara() {
		if(declaraList!=null&&declaraList.size()>0) {
			for(DeclaraListType item:declaraList) {
				List<XnType> list=item.getList();
				if(list!=null&&list.size()>0) {
					for(XnType t:list) {
						if(t instanceof DeclaraType) {
							DeclaraType dt=(DeclaraType)t;
							XnType type=dt.getType();
							//解析int类型
							if(type instanceof IntType) {
								String name=dt.getName().getName();
								symbolName.put(name, new SymbolType(1, name));
								DigitType digit=(DigitType)dt.getValue();
								String value="0";
								if(digit!=null) {
									value=digit.getValue();
								}
								code.append(name+":"+"\r\n");
								value=StringUtils.int2ByteStr(value);
								code.append("db "+value+"\r\n");
							}else if(type instanceof StringType) {
								String name=dt.getName().getName();
								symbolName.put(name, new SymbolType(4, name));
								StringValue value=(StringValue)dt.getValue();
								code.append(name+":"+"\r\n");
								code.append("db "+value.getValue()+"\r\n");
								code.append("db 0\r\n");
							}
						}
					}
				}
				
			}
		}
	}
	private void processFunction() {
		if(functionList!=null&&functionList.size()>0) {
			for(FunctionType function:functionList) {
				function.setParent(this);
				FunctionHeaderType head=(FunctionHeaderType)function.getFunctionHeader();
				IdType IdType=(IdType)head.getName();
				String name=IdType.getName();
				functionName.put(name, name);
				function.process();
				String funcCode=function.getAsmCode();
				if(funcCode!=null) {
					code.append(funcCode);
				}
			}
		}
	}
	
	public void process() {
		processDeclara();
		processFunction();
	}
	
	
	public SymbolType getSymbol(String name) {
		return symbolName.get(name);
	}
}
